import { useState } from 'react'
import {
  Table,
  Space,
  Button,
  Popconfirm,
  message,
  Modal,
  Form,
  Input,
  Upload,
  DatePicker,
  Select,
  Tooltip,
  Tag,
  InputNumber
} from 'antd'
import { useAntdTable, useRequest } from 'ahooks'
import { ColumnsType } from 'antd/lib/table'
import { pageReview, deleteReview, addOrUpdateReview, detailReview } from '@/service/review'
import { getGoalList } from '@/service/goal'
// import { useNavigate } from 'react-router-dom'
import { formatTime } from '@/utils'
import dayjs, { Dayjs } from 'dayjs'
import './index.less'

const today = ()=> dayjs()

export default function () {

  const { tableProps , run:reload } = useAntdTable(async ({ current , pageSize}) => {
    const {records , total } = await pageReview({
      current,
      pageSize
    })
    return {
      total,
      list:records
    }
  })

  const { data: goalList = [] } = useRequest(getGoalList)

  const [ addform ] = Form.useForm()

  const [ visible, setVisible ] = useState<boolean>(false)
  
  const [ isUpdate , setIsUpdate ] = useState<boolean>(false)

  const columns:ColumnsType<App.ReviewItem> = [
    {
      title: "总结日",
      dataIndex: 'review_date',
      align: 'center',
      render:(_ , record)=> formatTime(record.review_date, "YYYY-MM-DD")
    },
    {
      title: "用户",
      dataIndex:'user_id',
      align: 'center',
      render:()=> 'story'
    },
    {
      title: "状态",
      dataIndex:'review_status',
      align: 'center',
      render:(_ , record)=> `${record.review_status}%`
    },
    {
      title: '日记',
      dataIndex: 'remark',
      align: "center",
      width:200,
      render: (text , record) => (
        <Tooltip title={ record.remark }>
          <div className="remark">{ text}</div>
        </Tooltip>
      )
    },
    {
      title: '关联目标',
      dataIndex: 'goals',
      align: "center",
      render: (_, record) => {
        const goals = (record.goals || "").split(",")
        return (
          <Space size="small">
            {
              goals.map(goal => {
                return <Tag color="green" key={ goal }>{ goal }</Tag> 
              })
            }
          </Space>
        )
      }
    },
    {
      title: "创建时间",
      align: 'center',
      render:(_ , record)=> formatTime(record.create_time)
    },
    {
      title: "更新时间",
      dataIndex:'updated_time',
      align:'center',
      render:(_ , record)=> formatTime(record.updated_time)
    },
    {
      title: "操作",
      align:'center',
      render: (_ , record) => {
        return (
          <Space>
            <Popconfirm
              title="确认是否删除"
              onConfirm={async () => {
                const response = await deleteReview({ id: record.id })
                if (response) {
                  message.success("删除成功")
                  reload({...tableProps.pagination})
                } else {
                  message.error("删除失败")
                }
              }}
            >
              <Button type="link" size="small" danger>删除</Button>
            </Popconfirm>
            <Button
              size="small"
              type="link"
              onClick={async () => {
                setVisible(true)
                setIsUpdate(true)
                const {
                  id,
                  review_date,
                  remark,
                  goals,
                  review_status
                  // ... 
                } = await detailReview({ id: record.id }) || {};
                addform.setFieldsValue({
                  // ...
                  id,
                  review_date: dayjs(review_date),
                  remark,
                  goals,
                  review_status
                });
              }}
            >
              编辑
            </Button>
          </Space>
        )
      }
    },
  ]

  const onAdd = () => {
    addform.resetFields()
    setIsUpdate(false)
    setVisible(true)
  }

  const onPublish = async () => {
    const { review_date , ...rest } = addform.getFieldsValue();
    await addform.validateFields()
    const response = await addOrUpdateReview({
      review_date: (review_date as Dayjs).format("YYYY-MM-DD"),
      ...rest
    })
    if (response) {
      message.success(`${isUpdate ? '更新' : '新增' }成功`);
      setVisible(false)
      reload({...tableProps.pagination})
    } else {
      message.error(`${ isUpdate ? '更新' : '新增'}失败，请重新尝试`)
    }
  }

  return (
    <div className="review">
      <div className="action">
        <Button type="primary" onClick={onAdd}>新增</Button>
      </div>
      <Table
        bordered
        size="small"
        columns={columns}
        {...tableProps}
        rowKey="id"
      />
      <Modal
        title="今日总结"
        open={visible}
        onCancel={() => setVisible(false)}
        forceRender
        onOk={onPublish}
        bodyStyle={{paddingTop:'20px'}}
      >
        <Form
          layout="horizontal"
          form={addform}
          size="small"
          labelCol={{ span: 4 }}
          labelAlign="left"
          initialValues={{review_date:today() }}
        >
          <Form.Item
            label=""
            name="id"
            style={{ display: 'none' }}
          >
            <Input max={50}/>
          </Form.Item>
          <Form.Item
            label="总结日期"
            name="review_date"
            rules={[{ required: true, message: '必填' }]}
          >
            <DatePicker style={{width:'100%'}}/>
          </Form.Item>
          <Form.Item
            label="状态"
            name="review_status"
            rules={[{ required: true, message: '必填' }]}
          >
            <InputNumber
              formatter={(value) => `${value}%`}
              parser={(value) => value ? parseInt(value.replace('%', '')) : 0 }
            />
          </Form.Item>
          <Form.Item
            label="关联目标"
            name="goals"
            rules={[{ required: true, message: '必填' }]}
          >
            <Select mode="multiple">
              {
                goalList.map(goal => (
                  <Select.Option
                    value={goal.id}
                    key={goal.id}
                  >
                    {goal.title}
                  </Select.Option>
                ))
              }
            </Select>
          </Form.Item>
          <Form.Item
            label="每日日记"
            name="remark"
            rules={[{ required: true, message: '必填' }]}
          >
            <Input.TextArea/>
          </Form.Item>
          <Form.Item label="文件附件" name="file">
            <Upload fileList={[]}>
              <Button>上传</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}